package swing.dialog;

import api.UserApi;
import beanInfo.UserInfo;
import http.Response;
import model.ApiResultModel;
import myException.InputFormatException;
import myException.ServerConnectException;
import swing.customComp.HintJPasswordField;
import swing.customComp.HintJTextField;
import swing.customComp.CustomStyles;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

/**
 * 注册对话框
 */
public class RegisterDialog extends JDialog {

    public JPanel registerPanel;

    private JLabel accountStaticText;
    private HintJTextField accountField;
    private JLabel passwordStaticText;
    private HintJPasswordField passwordField;
    private JLabel verifyStaticText;
    private HintJPasswordField verifyPasswordField;
    private JButton registerButton;

    private ActionListener registerActionListener;

    public RegisterDialog(JFrame parentFrame) {
        super(parentFrame, false);
        this.setTitle("用户注册");
        this.setSize(400,450);
        this.setResizable(false);
        this.setLocationRelativeTo(parentFrame);
        registerPanel = new JPanel();
        registerPanel.setLayout(null);
        initAllComponent();
        addAllComponent();
        SwingUtilities.invokeLater(() -> registerButton.requestFocusInWindow());
        this.setContentPane(registerPanel);
    }

    private void initAllComponent() {
        accountStaticText = new JLabel("输入账户：");
        Font staticTextFont = new Font("宋体", Font.BOLD,16);
        accountStaticText.setFont(staticTextFont);
        accountStaticText.setBounds(30,20,200,20);
        //账户输入框
        accountField = new HintJTextField();
        accountField.setBounds(30, 45, 285, 35);
        accountField.setFont(CustomStyles.inputFont);
        accountField.setHintText("请输入4-24位字符的账户名");
        //静态文本
        passwordStaticText = new JLabel("输入密码：");
        passwordStaticText.setBounds(30,105,200,20);
        passwordStaticText.setFont(staticTextFont);
        //密码输入框
        passwordField = new HintJPasswordField();
        passwordField.setBounds(30, 130, 285, 35);
        passwordField.setEchoChar((char)0);
        passwordField.setHintText("请输入6-16位字符的密码");
        //静态文本
        verifyStaticText = new JLabel("确认密码：");
        verifyStaticText.setBounds(30,185,200,20);
        verifyStaticText.setFont(staticTextFont);
        //确认密码
        verifyPasswordField = new HintJPasswordField();
        verifyPasswordField.setBounds(30, 210, 285, 35);
        verifyPasswordField.setEchoChar((char)0);
        verifyPasswordField.setHintText("再次输入密码");
        //注册按钮
        registerButton = new JButton("注册");
        registerButton.setBounds(30, 300, 285, 35);
        registerActionListener = listen -> {
            String account = accountField.getText().trim();
            String pwd = passwordField.getText().trim();
            String verifyPwd = verifyPasswordField.getText().trim();
            new Thread(() -> {
                register(account, pwd, verifyPwd);
            }).start();
        };
        registerButton.addActionListener(registerActionListener);
    }

    private void addAllComponent() {
        registerPanel.add(accountStaticText);
        registerPanel.add(accountField);
        registerPanel.add(passwordStaticText);
        registerPanel.add(passwordField);
        registerPanel.add(verifyStaticText);
        registerPanel.add(verifyPasswordField);
        registerPanel.add(registerButton);
    }

    private void enterRegisterState() {
        SwingUtilities.invokeLater(() -> {
            registerButton.setText("注册中...");
            registerButton.removeActionListener(registerActionListener);
            accountField.setEnabled(false);
            passwordField.setEnabled(false);
            verifyPasswordField.setEnabled(false);
        });
    }

    private void exitRegisterState() {
        SwingUtilities.invokeLater(() -> {
            registerButton.setText("注册");
            registerButton.addActionListener(registerActionListener);
            accountField.setEnabled(true);
            passwordField.setEnabled(true);
            verifyPasswordField.setEnabled(true);
        });
    }

    public void register(String account, String pwd, String verifyPwd) {
        if (account.isEmpty() || pwd.isEmpty() || verifyPwd.isEmpty()) {
            showMessageDialog("输入不能为空！");
            return;
        }
        if (!pwd.equals(verifyPwd)) {
            showMessageDialog("两次输入的密码不一致");
            return;
        }
        if (!UserInfo.isAccountAndPwdLengthLegal(account, pwd)) {
            showMessageDialog("用户名或密码长度不合法！");
            return;
        }
        try {
            this.enterRegisterState();
            Response response = UserApi.register(account, pwd);
            if (response.getStatus_code() != Response.OK) {
                showMessageDialog(response.getStatus_code() + " " + response.getStatus_description());
                return;
            }
            ApiResultModel apiResult = ApiResultModel.fromJson(response.getBody());
            int result = showConfirmDialog(apiResult.getMessage());
            if (result == JOptionPane.OK_OPTION && apiResult.getCode() == ApiResultModel.SUCCESS_CODE) {
                this.dispose();
            }
        } catch (ServerConnectException e) {
            showMessageDialog("服务器连接失败！");
            e.printStackTrace();
        } catch (InputFormatException e) {
            showMessageDialog("数据格式错误！");
            e.printStackTrace();
        } finally {
            SwingUtilities.invokeLater(this::exitRegisterState);
        }
    }

    private void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(registerPanel, message);
    }

    private int showConfirmDialog(String message) {
        return JOptionPane.showConfirmDialog(registerPanel, message, "提示", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
    }
}
